<template>
  <div class="wrapper-home-page">
    <div class="home-page" id="top" ref="homePage">
      <van-row class="title_home" type="flex" align="center" :justify="isSeekJobPage ? 'space-around' : 'space-around'">
        <van-col span="1" class="city_home" @click="isSeekJobPage = false" v-show="isSeekJobPage" offset="1">
          <van-icon name="arrow-left" class="icon" color="#1989fa" />
        </van-col>

        <van-col span="4" class="city_home" @click="toAddressPage">
          <van-icon name="location-o" class="icon" color="#1989fa" />
          <span class="city">{{ addressValue | formatCityName }}</span>
        </van-col>

        <van-col span="19" class="search">
          <van-search
            show-action
            v-model="searchParams.keyword"
            placeholder="请输入搜索关键词"
            background="#E6E6E6"
            shape="round"
            clearable
            @clear="onClearAndReset"
            @keypress.enter="onSearch"
          >
            <template #left>
              <van-dropdown-menu style=''>
                <van-dropdown-item @change='changeSearch' v-model="searchValue" :options="option1" />
              </van-dropdown-menu>
            </template>
            <div slot="action" @click="onSearch">搜索</div>
          </van-search>
        </van-col>
      </van-row>

      <!-- <van-button type="primary" text="组件调用" @click="showNotify" /> -->


      <van-overlay :show="showOverlay" @click="scanjp()" class-name="over_layer">
        <van-cell-group class="layer">
          <van-cell value="扫一扫" />
        </van-cell-group>
      </van-overlay>
      <!-- <div style='height:40px;width:100%;background:red'>
        <a href="androidamap://navi?sourceApplication=appname&amp;poiname=fangheng&amp;lat=36.547901&amp;lon=104.258354&amp;dev=1&amp;style=2">导航</a>
      </div>-->
      <div v-show="smtype" class="num-mask" id="bcid"></div>

      <van-pull-refresh v-model="isRefreshing" @refresh="onRefresh">
        <van-swipe :autoplay="3000" class="my-swipe" indicator-color="white">
          <van-swipe-item v-for="(image, index) in images" :key="index">
            <van-image lazy-load :src="image" style="width: 100%" @click="doCopy" />
          </van-swipe-item>
        </van-swipe>
        <!-- 工作类型   -->
        <!--        <van-grid
          :gutter="5"
          class="jobType"
          :icon-size="20"
          column-num="3"
          v-show="!isSeekJobPage"
        >
          <van-grid-item
            v-for="(item, index) in jobTypeList"
            :icon="item.icon"
            :text="item.title"
            :key="index"
            @click="toSeekJobOrCV(item.id)"
          />
        </van-grid>-->

        <com-filter-bar
          @clickFilter="clickFilter"
          @getFilterBarVal="getFilterBarVal"
          :isDoFilter="isDoFilterAction"
        ></com-filter-bar>

        <div class="jobArr" style="margin-bottom:90px" v-if="jobList.length">
          <com-job-item
            v-for="item in jobList"
            :key="item.id"
            :jobItem="item"
            :serchType="1"
            :keyWord="'only_home'"
            @saveBrowsingHistoryList="toSaveBrowsingHistoryList"
          ></com-job-item>

          <van-pagination
            style="margin-top: 15px;"
            v-model="searchParams.pageIndex"
            :total-items="total"
            @change="handlePaginationChange"
            force-ellipses
          >
            <template #prev-text>
              <van-icon name="arrow-left" />
            </template>
            <template #next-text>
              <van-icon name="arrow" />
            </template>
            <template #page="{ text }">{{ text }}</template>
          </van-pagination>

          <nut-backtop style="bottom: 54px"></nut-backtop>
          <van-divider :style="{width: '100%', textAlign: 'center', color: '#747576', borderColor: '#747576'}">
            <div style @click="goPage('https://beian.miit.gov.cn/')">粤ICP备19036185号-2</div>
          </van-divider>
          <van-divider :style="{width: '100%', textAlign: 'center', color: '#747576', borderColor: '#747576'}">
            <div style @click="goPage('http://www.beian.gov.cn/')">公安备案号44030702003766</div>
          </van-divider>
        </div>
      </van-pull-refresh>
      <com-filter-popup ref="comFilterPopupRef" @getFilterPopUpVal="toGetFilterPopUpVal"></com-filter-popup>
      <div v-show="totalType == 0" class="totalType">您可以搜索公司名称或者手机号关注公司，或者通过链接和扫码关注公司，关注以后才能看到招聘信息。</div>
      <van-divider
        v-if="!jobList.length"
        :style="{
          position: 'absolute',
          bottom: '80px',
          width: '100%',
          textAlign: 'center',
          color: '#747576',
          borderColor: '#747576'
        }"
      >
        <div style @click="goPage('https://beian.miit.gov.cn/')">粤ICP备19036185号-2</div>
      </van-divider>
      <van-divider
        v-if="!jobList.length"
        :style="{
          position: 'absolute',
          bottom: '50px',
          width: '100%',
          textAlign: 'center',
          color: '#747576',
          borderColor: '#747576'
        }"
      >
        <div style @click="goPage('http://www.beian.gov.cn/')">公安备案号44030702003766</div>
      </van-divider>
    </div>

    <van-popup v-model:show="isPrivacy" round :overlay="true" data-disable-auto-close="false" :close-on-click-overlay="false">
        <div class="version_box">
          <div style="height:60vh;padding: 15px;" v-if="isPrivacyType == 0">
            <div class="title">欢迎使用您使用近聘</div>
            <div class="text">
              我们承诺会采取业界先进的安全措施保护您的信息安全，在您使用本应用时，我们会向您申请或获取定位、相机、相册、日历、麦克风、通知等权限，请知悉，您同意本弹窗内容相应设备权限并不会默认开启，我们会在您使用到相应业务功能时，另行弹窗征得您的同意后开启。同时我们需要您的设备信息、应用安装列表、日志信息用于信息发布、打击违法违规行为及防止平台用户个人信息泄露。提示您注意，我们仅向16周岁以上的用户提供求职招聘服务，如果您未满16周岁，请不要以任何方式使用我们服务。当我们得知我们无意中收集了16周岁以下人士的个人信息时，我们会根据适用法律法规进行删除或采取其他合适的措施。
            </div>
            <div class="text">点击同意，视为您已阅读并同意近聘
              <p>
                <span @click="isPrivacyType = 1">《近聘用户协议》</span>
                <span @click="isPrivacyType = 2">《隐私政策》</span>
              </p>
            </div>
            <div class="bottom">
              <span @click="refused">拒绝</span>
              <span class="agree" @click="agreeApp()">同意</span>
            </div>
          </div>
          <div style="height:60vh;padding: 15px;" v-if="isPrivacyType == 1">
            <userAgreement @changeIsPrivacy="changeIsPrivacy" :type="1"/>
          </div>
          <div style="height:60vh;padding: 15px;" v-if="isPrivacyType == 2">
            <privacyAgreement  @changeIsPrivacy="changeIsPrivacy" :type="1"/>
          </div>
        </div>
      </van-popup>
  </div>
</template>

<script>
import {Toast, Dialog, Notify, Pagination} from 'vant'

import banner_1 from '@/assets/img/home/banner_1.jpg'
import banner_2 from '@/assets/img/home/banner_2.jpg'
import banner_3 from '@/assets/img/home/banner_3.jpg'
import privacyAgreement from '../register/privacyAgreement.vue'
import userAgreement from '../register/userAgreement.vue'
import comJobItem from '../../components/comJobItem'
import comFilterBar from '../../components/comFilterBar'
import comFilterPopup from '../../components/comFilterPopup'
import {jobTypeList} from '../../constants/comUtils'
import {cityFilter, concatIds, storageHistoryLocation} from '../../utils/index'
import constant from '../../utils/constant'
import {formatCityName} from '../../utils/format'

import {mixin_one} from '../../mixin/mixin'

// 默认设置(缺省地址: 深圳市龙华区富士康科技集团龙华科技园)
import {LAT, LNG, CITY_ID, CITY_NAME} from '../../constants/location'
import {mapState, mapActions} from 'vuex'
import { union } from 'lodash-es'
let scan = null
export default {
  name: 'home',
  components: {
    comJobItem,
    comFilterPopup,
    comFilterBar,
    privacyAgreement,
    userAgreement
  },
  mixins: [mixin_one],
  data() {
    return {
      isPrivacy:false,
      isPrivacyType:0,
      scrollPosition: 0,
      isSeekJobPage: false,
      testId: '',
      smtype: false,
      show: false,
      showOverlay: false,
      jobTypeList,
      cityName: '',
      images: [banner_1, banner_2, banner_3],
      linkPhone: '13790143381',
      totalType: 1,
      jobList: [],
      isRefreshing: false,
      total: 0,
      saveBrowsingHistoryList: [],
      sqode: false,
      streetName: '',
      addressValue: '',
      searchParams: {
        homeType:0,
        // searchtype:'job',//job，company
        keyword: '', // 搜索关键字
        lng: null, // 经度
        lat: null, // 维度
        cityId: '', // 城市ID
        streetId: '', // 街道ID
        jobcategory: '', // 招聘类型(全职、兼职、小时工)
        order: '', // 排序字段
        minSalary: null, // 起始薪资
        maxSalary: null, // 最大薪资
        adrtype: '', // 按地址
        classproperties: '', // 班制属性
        jobattributes: '', // 职位属性
        benefits: '', // 福利列表
        paymode: '', // 算薪方式
        payday: '', // 发薪日
        payMoneyDetailDate: '', // 发薪日详细日期
        createTime: '', // 发布时间
        pageIndex: 1, // 当前页
        pageSize: 10 // 每页显示条数
      }, // 检索参数
      searchValue:'job',
      option1: [
        { text: '公司信息', value: 'job' },
        { text: '公司名称', value: 'company' },
      ],
    }
  },

  watch: {
    'searchParams.cityId': {
      handler: function(val) {
        let address = {
          type: '1', // 1为城市；2为街道
          id: this.searchParams.cityId,
          name: this.cityName
        }
        storageHistoryLocation(address)
      }
    },
    'searchParams.streetId': {
      handler: function(val) {
        let address = {
          type: '2', // 1为城市；2为街道
          id: this.searchParams.streetId,
          name: this.streetName
        }
        storageHistoryLocation(address)
      }
    }
    /*addressValue(val) {
      console.log('当前值', val)
      if (!(this.selectedAddress === 'val')){
        this.searchParams.pageIndex = 1
        this._getJobList()
      }
    },*/
  },

  // 匹配路由规则，进入该组件时被调用
  beforeRouteEnter(to, from, next) {
    // console.log('进入------该组件时被调用', to.meta.keepAlive, from.meta.keepAlive)
    // 一定要有next();
    next()
  },

  // 注意: 此处的逻辑(匹配路由规则，离开该组件时被调用)
  beforeRouteLeave(to, from, next) {
    // console.log('离开------该组件时被调用');
    if (to.name === 'jobDetail') {
      // 从详情页返回时缓存组件
      this.$route.meta.keepAlive = true
    } else {
      // 从地址页进入首页，则不缓存(需要重新加载)
      this.$route.meta.keepAlive = false
    }
    next()
  },

  mounted() {
    // 初始化signaR连接
    // this.signaR.connectServer()
    // window添加一个滚动滚动监听事件 todo 需要完善记录滚动条的位置
    window.addEventListener('scroll', this.handleScroll)
    // this.signaR.connectServer(this.allUserInfo.id)
    const recommendID = this.getUrlVars()['recommendID']
    console.log('recommendID推荐人id********', recommendID)
    const jobID = this.getUrlVars()['job_id']
    const type = this.getUrlVars()['type']
    const dataId = this.getUrlVars()['dataId']
    // let urlPath = JSON.stringify(window.location.href)
    // urlPath = urlPath.substring(0, urlPath.length - 3)
    // // console.log(urlPath)
    // var index = urlPath.lastIndexOf('\=')
    // urlPath = urlPath.substring(index + 1, urlPath.length)
    if (jobID) {
      this.$router.push({
        name: 'qode',
        query: {
          qodeType: recommendID,
          type: type,
          job_id: jobID,
          dataId: dataId
        }
      })
    }
    window.addEventListener('setItem', e => {})
  },

  filters: {
    formatCityName(cityName) {
      return formatCityName(cityName)
    }
  },

  activated() {
    // console.log('****执行activated*******', this.addressValue)
    // 缓存组件, 不可重新加载
    const paramLoading = {
      isLoading: false
    }
    this.handleCurrentAddress(paramLoading)
  },
  deactivated() {
    window.removeEventListener('scroll', this.handleScroll)
  },

  created() {
    let isLogin = localStorage.getItem('allCertificate')
    let isApp = localStorage.getItem('isAgree')
    if(!isApp&&isLogin){
      this.isPrivacy = true
    }
    // console.log('生命周期钩子函数 ****** created()')
    // 如果当前选择了地址则使用选择地址，否则使用定位地址
    if (
      localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS) &&
      localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS_VALUE)
    ) {
      const paramLoading = {
        isLoading: true
      }
      this.handleCurrentAddress(paramLoading)
    } else {
      // 配置一个默认地址(默认是: 深圳)
      this.initLocation()
      // Modified on 2023.04.10: 去除定位
      // 先使用ip定位（只能定位到地区范围，精度低但速度快）
      // this.getLngLatLocation()
      // 高精确定位（精度高但速度慢）
      // this.getLocation()
    }

    // 取出已保存的浏览记录
    const res = localStorage.getItem('saveBrowsingHistory')
    this.saveBrowsingHistoryList = JSON.parse(res) || []
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll)
  },

  methods: {
    changeSearch(){
      console.log(this.value1)
    },
    changeIsPrivacy(){
      this.isPrivacy = true
      this.isPrivacyType = 0
    },
    agreeApp(){
      this.isPrivacy = false
      localStorage.setItem('isAgree',1)
    },
    // 退出app
    refused(){
      plus.runtime.quit();
    },
    handleScroll() {
      let height = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      // console.log('当前的高度', height);
      localStorage.setItem('scrollPosition', height)
    },
    _toResetFilterPopup() {
      this.searchParams.classproperties = '' // 班制：两班倒、三班倒、、、
      this.searchParams.jobattributes = '' // 职位属性：坐班、站班
      this.searchParams.benefits = '' // 福利列表
      this.searchParams.paymode = '' // 算薪方式
      this.searchParams.payday = '' // 发薪日
      this.searchParams.payMoneyDetailDate = '' // 发薪日详细日期
      this.searchParams.createTime = '' // 发布时间
    },
    goPage(url) {
      window.location.href = url
    },
    getUrlVars() {
      var vars = {}
      let urlPath = JSON.stringify(window.location.href)
      urlPath = urlPath.substring(0, urlPath.length - 3)
      var parts = urlPath.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
        vars[key] = value
      })
      return vars
    },
    showOverlayClick() {
      this.showOverlay = true
      this.smtype = true
    },

    handlePaginationChange(pageIndex) {
      this.searchParams.pageIndex = pageIndex
      localStorage.setItem('home_pageIndex', pageIndex)
      this._getJobList()
    },

    goljin(result) {
      // console.log('goljin')
      if (result == 5) this.sqode = true
      if (result == 6) this.sqode = true
      if (result == 7) this.sqode = true
      if (result == 8) this.sqode = true
      if (result == 9) this.sqode = true
      if (result == 11) this.sqode = true
      if (this.sqode == true) {
        this.$router.push({
          name: 'qode',
          query: {
            qodeType: result
          }
        })
      } else {
        this.smtype = false
        Toast('请扫描近聘平台二维码')
      }
    },
    // H5调用扫描功能
    startRecognize() {
      let that = this

      if (!window.plus) return
      scan = new plus.barcode.Barcode('bcid')
      scan.onmarked = onmarked
      scan.start()
      function onmarked(type, result, file) {
        // console.log('result')
        // console.log(type)
        // console.log(result)
        // console.log('result')
        switch (type) {
          case plus.barcode.QR:
            type = 'QR'
            break
          case plus.barcode.EAN13:
            type = 'EAN13'
            break
          case plus.barcode.EAN8:
            type = 'EAN8'
            break
          default:
            type = '其它' + type
            break
        }
        result = result.replace(/\n/g, '')
        // console.log('aaaaaa')
        // console.log(result)
        // console.log('bbbbb')
        scan.close()
        //这里写扫码结束后 自己的逻辑
        // console.log('fsadfasfa')
        // that.smtype = false
        that.goljin(result)
      }
    },
    //扫一扫
    scanjp() {
      // this.$router.push('/tests')
      // location.href='http://sao315.com/w/api/saoyisao';

      // return false
      this.showOverlay = false
      let allCertificate = window.localStorage.getItem('allCertificate')
      // 有登录凭证才能看到
      if (allCertificate) {
        this.startRecognize()
      } else {
        this.$store.dispatch('logOut')
        Dialog.confirm({
          message: '此功能需要注册登入才能使用，为您跳转到注册登入页面。'
        })
          .then(() => {
            this.$router.push({
              path: '/login'
            })
          })
          .catch(() => {
            // on cancel
          })
      }
    },
    /** 处理当前选择的位置 */
    handleCurrentAddress(paramObj) {
      if (
        localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS) &&
        localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS_VALUE)
      ) {
        let address = JSON.parse(localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS))
        if (address.type === '1') {
          // 1为城市；2为街道
          this.searchParams.cityId = address.id
          this.cityName = address.name
          this.searchParams.streetId = ''
          this.streetName = ''
        } else if (address.type === '2') {
          this.searchParams.cityId = ''
          this.cityName = ''
          this.searchParams.streetId = address.id
          this.streetName = address.name
        }
        this.searchParams.lat = localStorage.getItem(constant.STORAGE_CURRENT_LAT)
        this.searchParams.lng = localStorage.getItem(constant.STORAGE_CURRENT_LNG)
        this.addressValue = localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS_VALUE)
        //this.addressValue = localStorage.getItem('STORAGE_LOCATION_CITY_NAME')
        this.searchParams.pageIndex = localStorage.getItem('home_pageIndex') * 1 || 1
        this.total = localStorage.getItem('home_count') * 1 || 0

        // todo 由于是多个页面集合在一起的, 还需要考虑: 缓存条件下, 考虑筛选条的值，
      }

      if (paramObj.isLoading) {
        // console.log('不----缓存组件了---需要发起请求')

        // 主要是为了覆盖原有值, 避免报错
        localStorage.setItem('home_pageIndex', '1')
        localStorage.setItem('home_count', '0')

        this.searchParams.pageIndex = 1
        this.total = 0

        this._getJobList()
      } else {
        // console.log('需要缓存组件')
        // 缓存组件, 需读取缓存数据就
        if (sessionStorage.getItem('jobListSessionStorage')) {
          this.jobList = JSON.parse(sessionStorage.getItem('jobListSessionStorage'))
          if (localStorage.getItem('scrollPosition')) {
            this.scrollPosition = localStorage.getItem('scrollPosition') * 1 || 0

            this.$nextTick(() => {
              document.body.scrollTop = this.scrollPosition
              document.documentElement.scrollTop = this.scrollPosition
              this.$refs.homePage.scrollTo(0, this.scrollPosition)
            })
          }
        }
      }
    },
    /*
    getLocationByGaode() {
      const self = this
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000
        })

        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, 'complete', onComplete)
        AMap.event.addListener(geolocation, 'error', onError)

        function onComplete(data) {
          // data是具体的定位信息
          console.log('定位成功信息：', data)
        }
      })
    },
    */
    /*
    getLngLatLocation() {
      AMap.plugin('AMap.CitySearch', function () {
        var citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // 查询成功，result即为当前所在城市信息
            console.log('通过ip获取当前城市：', result)
            //逆向地理编码
            AMap.plugin('AMap.Geocoder', function () {
              var geocoder = new AMap.Geocoder({
                // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                city: result.adcode
              })

              var lnglat = result.rectangle.split(';')[0].split(',')
              geocoder.getAddress(lnglat, function (status, data) {
                if (status === 'complete' && data.info === 'OK') {
                  // result为对应的地理位置详细信息
                  console.log(data)
                }
              })
            })
          }
        })
      })
    },
    */
    /**
     * 定位失败取默认配置数据：城市、经纬度
     */
    getLocation() {
      const self = this
      AMap.plugin('AMap.Geolocation', function() {
        let geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000
        })
        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, 'complete', onComplete)
        AMap.event.addListener(geolocation, 'error', onError)

        function onComplete(data) {
          // data是具体的定位信息
          // console.log('APP定位成功信息(%%%%% 精度高 %%%%%%):', data)
          let cityCode = data.addressComponent.citycode
          let city = cityFilter(cityCode)
          if (city) {
            self.$addStorageEvent(1, constant.STORAGE_LOCATION_CITY_ID, city.id)
            self.$addStorageEvent(1, constant.STORAGE_LOCATION_CITY_NAME, city.name)
            self.$addStorageEvent(1, constant.STORAGE_LOCATION_AD_CODE, data.addressComponent.adcode)
            self.$addStorageEvent(1, constant.STORAGE_LOCATION_TOWNSHIP, data.addressComponent.township)

            let address = {
              type: '1', // 1为城市；2为街道
              id: city.id,
              name: city.name
            }
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS, JSON.stringify(address))
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_LAT, data.position.lat)
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_LNG, data.position.lng)
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS_VALUE, city.name)
          }

          self.$addStorageEvent(1, constant.STORAGE_LOCATION_LAT, data.position.lat)
          self.$addStorageEvent(1, constant.STORAGE_LOCATION_LNG, data.position.lng)

          self.searchParams.pageIndex = 1
          self._getJobList()
          self.$store.state.user.currentLocationInfo = {
            isDefault: false,
            cityOrTown: city.name,
            currentLongitude: data.position.lng,
            currentLatitude: data.position.lat,
            currentAddress: '我的位置',
            currentFullAddress: '我的位置'
          }
          // console.log(self.$store.state.user.currentLocationInfo)
        }

        function onError(data) {
          // 定位出错
          console.log('APP定位失败错误：', data)
          // 调用ip定位
          // self.getLngLatLocation()
        }
      })
    },

    getLngLatLocation() {
      const self = this
      AMap.plugin('AMap.CitySearch', function() {
        let citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // 查询成功，result即为当前所在城市信息
            // console.log('APP通过ip获取当前城市($$$$$$ 速度快 [(外)层数据 ]  $$$$$ )result为: ', result)
            //正向地理编码
            AMap.plugin('AMap.Geocoder', function() {
              let geocoder = new AMap.Geocoder({
                // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                city: result.adcode
              })
              // 根据编码值, 获取经纬度
              geocoder.getLocation(result.city, function(status, data) {
                if (status === 'complete' && data.info === 'OK') {
                  // result为对应的地理位置详细信息
                  // console.log("APP通过ip获取当前地理位置(##### 速度快 { (内) 层数据 } #####)data为:", data)
                  let cityCode = data.geocodes[0].addressComponent.citycode
                  let city = cityFilter(cityCode)
                  if (city) {
                    self.$addStorageEvent(1, constant.STORAGE_LOCATION_CITY_ID, city.id)
                    self.$addStorageEvent(1, constant.STORAGE_LOCATION_CITY_NAME, city.name)
                    self.$addStorageEvent(1, constant.STORAGE_LOCATION_AD_CODE, result.adcode)
                    self.$addStorageEvent(1, constant.STORAGE_LOCATION_LNG, data.geocodes[0].location.lat)
                    self.$addStorageEvent(1, constant.STORAGE_LOCATION_LAT, data.geocodes[0].location.lng)

                    let address = {
                      type: '1', // 1为城市；2为街道
                      id: city.id,
                      name: city.name
                    }
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS, JSON.stringify(address))
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_LAT, data.geocodes[0].location.lat)
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_LNG, data.geocodes[0].location.lng)
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS_VALUE, city.name)
                  }

                  self.searchParams.pageIndex = 1
                  self._getJobList()
                }
              })
            })
          }
        })
      })
    },

    // 初始化位置信息
    initLocation() {
      this.searchParams.cityId = localStorage.getItem(constant.STORAGE_LOCATION_CITY_ID)
        ? localStorage.getItem(constant.STORAGE_LOCATION_CITY_ID)
        : ""

      this.searchParams.lng = localStorage.getItem(constant.STORAGE_LOCATION_LNG)
        ? localStorage.getItem(constant.STORAGE_LOCATION_LNG)
        : LNG

      this.searchParams.lat = localStorage.getItem(constant.STORAGE_LOCATION_LAT)
        ? localStorage.getItem(constant.STORAGE_LOCATION_LAT)
        : LAT

      this.cityName = localStorage.getItem(constant.STORAGE_LOCATION_CITY_NAME)
        ? localStorage.getItem(constant.STORAGE_LOCATION_CITY_NAME)
        : "全国"

      this.addressValue = this.cityName

      this.searchParams.pageIndex = 1
      this._getJobList()
    },

    // 公共函数
    async _getJobList() {
      // const res = await this.$api.myCompany.getMyCompanyJobPage(this.searchParams)
      // this.searchParams.searchtype = this.searchValue
      const res = await this.$api.job.getJobPage(this.searchParams)
      if (res.code === 200) {
        sessionStorage.setItem('jobListSessionStorage', JSON.stringify(res.data.items))
        this.jobList = res.data.items
        this.total = res.data.count
        localStorage.setItem('home_count', res.data.count)

        if (this.total == 0) this.totalType = 0
      }
    },

    toGetFilterPopUpVal(val, val_2) {
      this.searchParams.classproperties = val.select_class_id // 班制：坐班、站班
      this.searchParams.jobattributes = val.select_position_attribute_id // 职位属性：两班倒、三班倒、、、
      this.searchParams.benefits = concatIds(val.select_welfare_list) // 福利列表
      this.searchParams.paymode = val.select_payWay_id // 算薪方式
      this.searchParams.payday = val.select_payMoneyDay_id // 发薪日
      this.searchParams.payMoneyDetailDate = val.select_payMoneyDay_detail // 发薪日详细日期
      this.searchParams.createTime = val.select_publish_date // 发布时间

      console.log('searchParams:', this.searchParams)

      // console.log('新需求参数：', val_2);
      this._updateFilterOperationObj(val_2)

      this.searchParams.pageIndex = 1
      this._getJobList()
    },

    getPaginationValue_home(val) {
      // 指定页
      this.searchParams.pageIndex = val.pageIndex
      this._getJobList()
    },

    toSaveBrowsingHistoryList(val) {
      // 仅用于点击首页的工作，点击保存记录
      // 若没有找到了, 则结果为undefined
      if (val) {
        val.recordTime = new Date()
      }
      this.saveBrowsingHistoryList.unshift(val)
      localStorage.setItem('saveBrowsingHistory', JSON.stringify(this.saveBrowsingHistoryList))
    },

    toSeekJobOrCV(id) {
      if (id === '4') {
        // 跳转至简历页面
        this.$router.push('/resume')
      } else {
        // this.$router.push({
        //   path: '/seekJob',
        //   query: {
        //     id
        //   }
        // })
        this.searchParams.jobcategory = id
      }
    },

    // 点击筛选
    clickFilter() {
      // 通过props父组件的方法，可实现子组件向父组件中传值
      let filterPopupRef = this.$refs.comFilterPopupRef
      // 父组件调用子组件中的方法
      filterPopupRef.changeFilterPopupState()
    },
    getFilterBarVal(needParamObj) {
      Object.assign(this.searchParams, needParamObj)
      this._getJobList()
    },

    onRefresh() {
      // 初始化页面： 将页面置为1。
      this.searchParams.pageIndex = 1
      this._getJobList()
      this.isRefreshing = false
    },

    onSearch() {
      console.log(this.searchValue)
      if (this.searchParams.keyword && this.searchParams.keyword.trim()) {
        // console.log('执行刷新')
        this.searchParams.pageIndex = 1
        this._getJobList()
      }
    },
    onClearAndReset() {
      // console.log('取消清除按钮')
      this.searchParams.pageIndex = 1
      this._getJobList()
    },

    doCopy: function() {
      this.$copyText(this.linkPhone).then(
        function(e) {
          Toast('复制成功, 将联系方式粘贴到手机电话即可联系，或粘贴添加微信。')
        },
        function(e) {
          Toast('复制出错')
        }
      )
    },

    toJobDetailPage(id) {
      this.$router.push({
        path: `/jobDetail/${id}`
      })
    },

    /** 打开地址选择页 */
    toAddressPage() {
      this.$router.push({
        name: 'selectAddress'
        // query: {pre: 'home'}
      })
    }
  }
}
</script>

<style lang="scss" scoped>
:deep .van-overlay{
  background: #000;
}
:deep .van-dropdown-menu__title::after{
  opacity: 0;

}
.version_box{
  height:60vh;
  width:80vw;
  // position: static;
  .title{
    font-size: 18px;
    height:30px;
    line-height: 30px;
    font-weight: 700;
  }
  .text{
    font-size: 14px;
    p{
    span{
      color:#84b9b7;
    }

    }
  }
  .bottom{
    display: flex;
    justify-content: flex-end;
    font-size: 14px;
    color:#ddd;
    span{
      padding: 5px 10px;
    }
    .agree{
      color:#84b9b7;

    }
  }
}
.wrapper-home-page {
  width: 100%;
  min-height: 100vh;
  //border: 2px solid red;
  box-sizing: border-box;
  overflow: hidden;
  // white-space: nowrap;
  .home-page {
    width: 100%;
    min-height: 100vh;
    box-sizing: border-box;
    position: absolute;
    .record {
      position: absolute;
      width: 100%;
      height: 30px;
      line-height: 30px;
      bottom: 0;
      text-align: center;
      .text {
      }
    }
    .title_home {
      height: 46px;
      line-height: 46px;
      text-align: center;
      background-color: #e6e6e6;
      color: #1989fa;
      .city_home {
        font-size: 14px;
        height: 34px;
        line-height: 34px;
        display: flex;
        justify-content: center;
        align-items: center;
        .icon {
          font-size: 19px;
        }
        .city {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
      .search {
        /deep/ .van-search {
          padding: 0;
        }
      }
      :deep .van-dropdown-menu__bar{
        height:20px;
        font-size: 14px;
        background: #e6e6e6;
      }
    }
    .over_layer {
      margin-top: 46px;
      height: 100%;
      .layer {
        width: 30%;
        font-size: 14px;
        position: absolute;
        right: 0;
        z-index: 2;
      }
    }
    .my-swipe {
      width: 100%;
      height: 200px;
      overflow: hidden;
    }
    .jobType {
      background-color: #ffffff;
    }
    .totalType {
      padding: 5px 10px;
      font-size: 16px;
      color: #e4393c;
      white-space: normal;
    }
    .num-mask {
      width: 100%;
      height: 100%;
      position: fixed;
      left: 0;
      // top: 10%;
      background: rgba(0, 0, 0, 1);
      z-index: 0;
    }
    .title {
      width: 100%;
      position: absolute;
      top: 0;
      height: 40px;
      line-height: 40px;
      text-align: center;
      font-size: 2rem;
    }
  }
}
</style>
